package com.suning.sawp.service.impl.precharge;

import javax.annotation.Resource;

import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import com.suning.sawp.intf.precharge.SequenceSerivce;
import com.suning.sawp.po.precharge.Sequence;

/**
 * 
 * 〈一句话功能简述〉<br> 
 * 〈功能详细描述〉
 *
 * @author 12061818
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service
public class SequenceServiceImpl implements SequenceSerivce {

    
    @Resource
    MongoOperations mongoTemplate;
    
    private static final long INCR = 1;
    
    @Override
    public void addNewSequence(String key, long initVal) {
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.and(Sequence.Attributes.KEY).is(key);
        query.addCriteria(criteria);
        // 判断此类别序列器是否已存在
        if (!mongoTemplate.exists(query, Sequence.class)) {
            // 不存在新增
            mongoTemplate.insert(new Sequence(key, initVal));
        }
    }

    @Override
    public String incrSequenceNumber(String key) {
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.and(Sequence.Attributes.KEY).is(key);
        query.addCriteria(criteria);
        
        Update update = new Update();
        update.inc(Sequence.Attributes.VALUE, INCR);
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.remove(false);
        options.returnNew(true);// 返回更新后值
        options.upsert(true);
        Sequence result = mongoTemplate.findAndModify(query, update, options, Sequence.class);
        return String.valueOf(result.getValue());
    }

}
